package start.demo01.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;

public class Task {
    public static void main(String[] args) throws FileNotFoundException {
        File file=new File("D:\\FilePath\\IDEA\\demo/books.xml");
        System.out.println(file.length());
        parseXml(new FileInputStream(file));
    }
    public static void parseXml(InputStream is){
        try{
            DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
            DocumentBuilder builder=factory.newDocumentBuilder();
            Document document=builder.parse(is);
//            NodeList list = document.getElementsByTagNameNS("books", "name");
//            System.out.println(list.getLength());
            NodeList nodeList = document.getElementsByTagName("book");
            node(nodeList);
//            Element root=document.getDocumentElement();
//            NodeList nodes=root.getChildNodes();
//            for(int i=0;i<nodes.getLength();i++){
//                Element node=(Element)nodes.item(i);
//                Integer id=Integer.parseInt(node.getAttribute("id"));
//                NodeList childNodes=node.getChildNodes();
//
//            }

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void node(NodeList list){
        for (int i = 0; i <list.getLength() ; i++) {
            Node node = list.item(i);
            NodeList childNodes = node.getChildNodes();
            for (int j = 0; j <childNodes.getLength() ; j++) {
                if (childNodes.item(j).getNodeType()==Node.ELEMENT_NODE) {
                    System.out.print(childNodes.item(j).getNodeName() + ":");
                    System.out.println(childNodes.item(j).getFirstChild().getNodeValue());
                }
            }
        }
    }
}
